const router = require('koa-router')()
const upload = require('../upload')
const mongoose = require('mongoose')

const Image = mongoose.model('Image')
const Comment = mongoose.model('Comment')
const statsfn = require('../lib/statsfn')

router.prefix('/images')

router.post('/', upload.single('imgfile'), async function (ctx) {
    const { title, description } = ctx.req.body
    const { originalname, mimetype, filename: diskfilename } = ctx.req.file
    const username = ctx.session.username
    const doc = await Image.create({
        title, description, originalname, mimetype, diskfilename, username, imageauthor: ctx.session.username 
    })
    ctx.redirect(`/images/${doc._id}`)
    console.log(username)
})



router.get('/:imageid', async ctx => {
    const doc = await Image.findByIdAndUpdate(
      ctx.params.imageid,
      {$inc: {visit: 1}},
      {new: true}
    )
    doc.stats = await statsfn()
    doc.comments = await Comment
      .find({image: ctx.params.imageid})
      .sort({ createdAt: -1 })
    doc.commentlast = await Comment.find({})
      .sort({createdAt: -1}).limit(3)
    if (doc) {
        await ctx.render('show', doc)
    }
})

router.post('/likes/:imageid', async ctx => {
    const doc = await Image.findByIdAndUpdate(
        ctx.params.imageid,
        { $inc: { likes: 1 } },
        { new: true }
    )
    ctx.body = doc
})

module.exports = router